<template>
  <div class="about">
    <!--搜索-->
        <el-row>
            <el-col :span="6">
                <el-input v-model="dname" size="mini" auto-complete="off" placeholder="请输入角色名称"></el-input>
            </el-col>
            <el-col :span="6"><el-button type="primary" @click="search"  size="mini" icon="el-icon-search">搜索</el-button>
            &nbsp;<el-button type="primary"  size="mini" icon="el-icon-circle-plus" @click="handleAdd">添加</el-button></el-col>
            <el-col :span="6"><div class="grid-content bg-purple-light">&nbsp;</div></el-col>
        </el-row>
        <!--分页列表显示 -->
        <el-row>
            <el-table
                    :data="tableData"
                    style="width: 100%">       
                <el-table-column
                    prop="roleName"
                    label="角色名称"
                    width="280">
                </el-table-column>           
                <el-table-column label="角色状态">
                    <template slot-scope="scope">
                        {{ scope.row.status == 0 ? '正常':'停用'}}
                    </template>
                </el-table-column>                
                <el-table-column
                    prop="createBy"
                    label="创建人">
                </el-table-column>     
                <!-- <el-table-column
                    prop="createTime"
                    label="添加时间"
                    value-format="yyyy-MM-dd HH:mm:ss">
                </el-table-column>              -->
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button
                                    type="primary"
                                    size="mini"
                                    @click="toShowMenuTree(scope.$index, scope.row)">角色授权</el-button>
                        <el-button
                                size="mini"
                                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>
        <!--分页插件-->
        <el-row>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[2,3,5,10,100, 200, 300, 400]"
                    :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-row>
        <!--添加和更新 弹框-->
        <el-row>
            <!--添加 弹框-->
            <el-dialog :title="title" :visible.sync="dialogFormVisibleAdd">
                <el-form :model="form">
                    <el-form-item label="角色名称" >
                        <template>
                            <el-select v-model="form.roleName" placeholder="请选择">
                                <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                            </el-select>
                        </template>
                    </el-form-item>
                    <el-form-item label="数据范围" >
                        <el-radio v-model="form.dataScope" label="1">全部数据权限</el-radio>
                        <el-radio v-model="form.dataScope" label="2">自定义数据权限</el-radio>
                    </el-form-item>
                    <el-form-item label="角色状态" >
                        <el-radio v-model="form.status" label="0">正常</el-radio>
                        <el-radio v-model="form.status" label="1">停用</el-radio>
                    </el-form-item>
                    <el-form-item label="创建人" >
                        <el-input v-model="form.createBy" auto-complete="off"></el-input>
                    </el-form-item>                
                    <!-- <el-form-item label="更新者" >
                        <el-input id="abc" v-model="form.updateBy" auto-complete="off"></el-input>
                    </el-form-item> -->
                    <el-form-item label="备注" >
                        <el-input v-model="form.remark" auto-complete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisibleAdd = false">取 消</el-button>
                    <el-button type="primary" @click="addOrUpdate">确 定</el-button>
                </div>
            </el-dialog>
            <!--更新 弹框-->
            <el-dialog :title="title" :visible.sync="dialogFormVisibleUpdate">
                <el-form :model="form">
                    <el-form-item label="角色名称" >
                        <template>
                            <el-select v-model="form.roleName" placeholder="请选择">
                                <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                            </el-select>
                        </template>
                    </el-form-item>
                    <el-form-item label="数据范围" >
                        <el-radio v-model="form.dataScope" label="1">全部数据权限</el-radio>
                        <el-radio v-model="form.dataScope" label="2">自定义数据权限</el-radio>
                    </el-form-item>
                    <el-form-item label="角色状态" >
                        <el-radio v-model="form.status" label="0">正常</el-radio>
                        <el-radio v-model="form.status" label="1">停用</el-radio>
                    </el-form-item>
                    <!-- <el-form-item label="创建人" >
                        <el-input v-model="form.createBy" auto-complete="off"></el-input>
                    </el-form-item>                 -->
                    <el-form-item label="更新者" >
                        <el-input id="abc" v-model="form.updateBy" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="备注" >
                        <el-input v-model="form.remark" auto-complete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisibleUpdate = false">取 消</el-button>
                    <el-button type="primary" @click="addOrUpdate">确 定</el-button>
                </div>
            </el-dialog>
            <!--角色授权弹出框-->
            <el-dialog title="权限菜单" :visible.sync="menuTreeVisible">
                <el-tree :data="data"
                         :props="defaultProps"
                         node-key="id"
                         show-checkbox
                         ref="menuTree"
                         :default-checked-keys="nodeChecked"
                         default-expand-all
                ></el-tree>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="addRoleAndMenus()">确 定</el-button>
                </div>
            </el-dialog>
        </el-row>
  </div>
</template>
<script>
export default {
      data() {
        return {
                data:[], //当前所有的权限
                defaultProps: {
                     children: 'children',
                     label: 'label'
                },
                tableData:[], //所有用户
                currentPage:1,//当前页面，默认1
                pageSize:5,//每页显示条数
                total:100,//分页总数量，默认值随便写，初始化时赋予新值
                dname:'',//查询功能
                roleId:0, //当前选中的用户ID
                dialogFormVisibleUpdate:false,
                dialogFormVisibleAdd:false,
                title:'部门添加',
                form:{},                
                addFormVisible:false,//添加对话框是否显示
                updateFormVisible:false,//更新对话框是否显示                
                formLabelWidth:"120px",
                roleId:0,//角色id
                menuTreeVisible:false,
                nodeChecked:[], //默认角色选中的权限菜单
                options: [{
                value: '管理员',
                label: '管理员'
                }, {
                value: '代理商',
                label: '代理商'
                }, {
                value: '商户',
                label: '商户'
                }, {
                value: '培训管理员',
                label: '培训管理员'
                }, {
                value: '经理',
                label: '经理'
                }],
                value: ''
                }
            },
      
       created:function(){
               //初始化
                this.loadData();
            },
        methods:{
                //加载数据
                loadData(){
                   //动态菜单请求
                          this.$http.post("/api/cs/role/queryAll?pageNo="+this.currentPage+"&pageSize="+this.pageSize,{
                              params:{
                                            roleName:this.dname
                                    }
                             }).then((response) => {
                                                 console.log(response);
                                              if(response.data.code==2000){
                                                  this.tableData = response.data.data.list;
                                                  this.total = response.data.data.total;
                                              }
                                })                                          
                },
                
                //各种绑定事件方法
                //每页数量发生变化
                handleSizeChange(val) {
                    console.log(`每页 ${val} 条`);
                    this.pageSize=val;
                    this.loadData();               
                },
                //当前页发生变化
                handleCurrentChange(val) {
                    console.log(`当前页: ${val}`);
                    this.currentPage=val;
                    this.loadData();                   
                },
                //查询方法
                search(){
                   this.loadData();
                },

                //弹出权限菜单对话框
                 toShowMenuTree:function (index,row){
                     //给角色ID复
                     this.roleId=row.roleId;               
                     var _this =this;
                     //this.nodeChecked=[];  解决不了缓存问题
                     //初始化数据
                     this.$http.get('/api/cs/menu/queryNodes')
                         .then(function (response) {
                             let tmpData=response.data.data;
                            //  console.log("所有权限查询"+response.data.code)
                            //  console.log("选中用户ID"+_this.roleId)
                             //查询并给勾选项赋值
                             _this.$http.get('/api/cs/role/listMenuByRoleId?roleId='+_this.roleId)
                                 .then(function (response) {
                                    //  console.log("该角色有的权限"+response.data.code)
                                      /*for (var i = 0; i < response.data.data.length; i++) {
                                          console.log(response.data.data[i])
                                         _this.nodeChecked.push(response.data.data[i].id);
                                      };*/
                                     _this.data=tmpData;
                                     //根据角色ID查出权限菜单ID，赋值给nodeChecked
                                     _this.nodeChecked=response.data;
                                    // console.log("...222....."+ _this.nodeChecked)
                                 });
                         });
                     //显示权限菜单对话框
                     this.menuTreeVisible=true;
                 },
                 //添加角色和权限菜单关联方法
                 addRoleAndMenus(){
                    //获取重新选中的节点
                    let nodes = this.$refs.menuTree.getCheckedNodes();
                    //判断至少选中一个节点
                    if(nodes.length<1){
                        this.$message.error("至少选中一个节点");
                        return;
                    }
                    let tempMenuIds="";
                    //循环遍历
                     for (var i = 0; i < nodes.length; i++) {
                         tempMenuIds+=nodes[i].id+",";
                     }
                     tempMenuIds=tempMenuIds.substr(0,tempMenuIds.length-1);
                     console.log("当前角色为："+this.roleId+"，该角色对应新的权限ID为："+tempMenuIds);
                     var _this =this;
                     //执行后台添加方法
                     this.$http.post('/api/cs/role/addRoleAndMenu?roleId='+this.roleId+"&menuIds="+tempMenuIds).then(function (response) {
                         console.log(response);
                         if(response.status == 200){                       
                             if(response.data.data>0) {
                                //提示成功
                                _this.$message({
                                    type: 'success',
                                    message: '授权成功!'
                                });
                                //关闭弹框
                                _this.menuTreeVisible=false;
                                //重新加载数据
                                _this.loadData();
                             }
                         }
                     }).catch(function (error) {
                         console.log(error);
                         _this.$message.error("你错了。。。");
                     });
                 },

                //处理添加
                handleAdd(){
                    //清空原来form
                    this.form={};
                    //更新显示名称
                    this.title="用户添加";
                    //对话框显示
                    this.dialogFormVisibleAdd=true;
                },
                //处理编辑（弹出部门更新对话框）
                handleEdit(index, row) {
                    console.log(index, row);
                    this.form =  JSON.parse(JSON.stringify( row));
                    //更新显示名称
                    this.title="用户更新";
                    //对话框显示
                    this.dialogFormVisibleUpdate=true;
                },

                //提交表单数据（添加或者更新）
                addOrUpdate(){
                    var  url ='/api/cs/role/update';
                    if(this.form.roleId==''||this.form.roleId==null){
                        url="/api/cs/role/insert"
                    }
                    var _this=this;
                    //提交方法
                    this.$http.post(url, this.form)
                        .then(function (response) {
                            console.log(response);
                            //提交成功
                            if(response.data.code==2000){
                                //关闭弹出框
                                _this.dialogFormVisibleAdd=false;
                                _this.dialogFormVisibleUpdate=false;
                                //提示更新成功
                                _this.$message({
                                  //  message: '恭喜你，这是一条成功消息',
                                    message: response.data.message,
                                    type: 'success'
                                });
                                //重新加载数据
                                _this.loadData();
                            }else {
                                _this.$message.error(response.data.message);
                            }
                        })
                        .catch(function (error) {
                            _this.$message.error('错了哦，这是一条错误消息');
                        });
                },
                //处理删除（ 部门删除）
                handleDelete(index, row) {
                    console.log(index, row);
                    var _this=this;
                    //确认弹框
                    _this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        //执行删除
                        this.$http.delete('/api/cs/role/deleteById?roleId='+row.roleId)
                            .then(function (response) {
                                //判断删除是否成功
                                 if(response.data.code==2000){
                                     //提示
                                     _this.$message({
                                         type: 'success',
                                         message: '删除成功!'
                                     });
                                     //重新加载数据
                                     _this.loadData();
                                 }else {
                                     _this.$message.error(response.data.message);
                                 }
                            })
                            .catch(function (error) {
                                //失败处理
                                console.log(error);
                                _this.$message.error('删除失败!');
                            });
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });


                }
            }
    }
</script>
<style>

</style>
